import 'dart:convert';

import 'package:flutter_soundmagus/model/model.dart';
import 'package:flutter_soundmagus/util/ble_helper.dart';
import 'package:rxdart/subjects.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart';
part 'data_mng_part.dart';

class DataMng {
  static final DataMng shared = DataMng._();
  static final String _dataKey = 'dsp_cache';

  XoverModel xoverModel = XoverModel();
  EQModel eqModel = EQModel();
  SUMMINGModel summingModel = SUMMINGModel();
  AdvancedModel advancedModel = AdvancedModel();

  final subject = PublishSubject<DataMng>();

  DataMng._() {
    loadFromCache();
  }

  ///通道名称
  final chNames = List.generate(kChCount, (index) => 'CH${index + 1}'.obs);

  void notifyListener() {
    subject.add(this);
  }

  factory DataMng() {
    return shared;
  }

  static void reset() {
    shared
      ..xoverModel = XoverModel()
      ..eqModel = EQModel()
      ..summingModel = SUMMINGModel()
      ..advancedModel = AdvancedModel();
  }

  ///保存到本地默认位置
  Future<bool> save() async {
    var str = getSaveString();
    var pref = await SharedPreferences.getInstance();
    return pref.setString(_dataKey, str);
  }

  ///获取当前数据的字符串形式
  String getSaveString() {
    var str = [
      xoverModel.toJson(),
      eqModel.toJson(),
      summingModel.toJson(),
      advancedModel.toJson()
    ].map((e) => jsonEncode(e)).join('##');
    return str;
  }

  ///清除本地缓存
  Future<bool> cleanCache() async {
    var pref = await SharedPreferences.getInstance();
    return pref.setString(_dataKey, '');
  }

  ///从本地缓存加载eq等数据
  void loadFromCache() async {
    var pref = await SharedPreferences.getInstance();
    var str = pref.getString(_dataKey);
    if (str != null && str.isNotEmpty) {
      try {
        loadFromString(str, coverthis: true);
      } catch (e) {
        await cleanCache();
      }
      notifyListener();
    }
  }

  ///从字符串加载eq、xove等数据[coverthis]覆盖当前DataMng
  List<dynamic>? loadFromString(String str, {bool coverthis = false}) {
    if (str.isNotEmpty) {
      var datas = str.split('##').map((e) => jsonDecode(e)).toList();
      if (datas.length == 4) {
        var xoverModel = XoverModel.fromJson(datas[0]);
        var eqModel = EQModel.fromJson(datas[1]);
        var summingModel = SUMMINGModel.fromJson(datas[2]);
        var advancedModel = AdvancedModel.fromJson(datas[3]);
        if (coverthis) {
          this
            ..xoverModel = xoverModel
            ..eqModel = eqModel
            ..summingModel = summingModel
            ..advancedModel = advancedModel;
        }
        return [xoverModel, eqModel, summingModel, advancedModel];
      }
    }
    return null;
  }

  ///转换成分享的指令
  String? shareCmdString(String str) {
    var list = loadFromString(str, coverthis: false);
    if (list?.length != 4) return null;

    XoverModel xoverModel = list![0];
    EQModel eqModel = list[1];
    SUMMINGModel summingModel = list[2];
    AdvancedModel advancedModel = list[3];

    return [
      xoverModel.toCmdStr(),
      eqModel.toCmdStr(),
      summingModel.toCmdStr(),
      advancedModel.toCmdStr(),
    ].join();
  }
}
